package org.blade.personal.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.blade.personal.component.Const;
import org.blade.personal.manager.sys.UserManager;
import org.blade.personal.mode.sys.SystemUser;
import org.blade.personal.utils.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("usr")
public class UsrController {

	@Autowired
	private UserManager userManager;
	/**
	 * 用户管理
	 * @return
	 */
	@RequestMapping("show")
	public ModelAndView showList(){
		ModelAndView to = new ModelAndView("user/user-mgr");
		to.addObject("title", "清单");
		return to;
	}
	
	/**
	 * 添加角色
	 * @return
	 */
	@RequestMapping("toEdit")
	public ModelAndView toEdit(){
		ModelAndView to = new ModelAndView("edit");
		to.addObject("title", "用户编辑");
		to.addObject(Const.System.MODULE, Const.System.USER);
		return to;
	}
	
	@ResponseBody
	@RequestMapping("save")
	public int saveRoles(@RequestParam Map data){
		String userJson = MapUtils.getString(data, Const.Buesiness.DATA);
		try{
			SystemUser user = JSON.parseObject(userJson, SystemUser.class);
			userManager.saveUser(user);
			return Const.Status.SUCCESS;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return Const.Status.FAIL;

	}
	
	/**
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("fetch")
	public Map<String,Object> fetchUsers(@RequestParam Map<String,Object> data){
		
		Pager<SystemUser> page = new Pager<SystemUser>();
		page.setCurrentPage(MapUtils.getLong(data, "page"));
		page.setPageSize(MapUtils.getLong(data, "pagesize"));
		String userJson =  MapUtils.getString(data, "params");
		SystemUser user = JSON.parseObject(userJson, SystemUser.class);
		userManager.pagination(page, user);
		data.put("datas", page.getEntities());
		data.put("Total", page.getTotalCount());
		return data;
	}
	
	@ResponseBody
	@RequestMapping("delete")
	public int deleteUser(@RequestParam Map reqParam){
		String userJson = MapUtils.getString(reqParam,"user");
		List<SystemUser> users = JSON.parseArray(userJson, SystemUser.class); 
		return userManager.deleteUser(users.get(0));
	}
	
	@ResponseBody
	@RequestMapping("load")
	public SystemUser load(@RequestParam Map data){
		Long id = MapUtils.getLong(data, Const.System.ID);
		return userManager.getById(id);
	}
	
	/**
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getAllUsers")
	public List<SystemUser> getAllUsers(){
		return userManager.getAllUsers();
	}
	
}
